package com.ruoyi.womp.task;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.womp.service.ISqlQueryService;
import com.ruoyi.womp.tools.DateUtil;

@Component("hisDataTask")
public class HisDataTask {

	final static String TASK_NAME = "历史数据处理任务";

	@Autowired
	MongoTemplate mongoTemplate;

	@Autowired
	ISqlQueryService sqlQueryService;

	final String WSMS_REALTIME_DATA_TABLE = "womp_realtime_data";

	public void execute() {
		handleData();
	}

	private void handleData() {
		try {

			String sql = "select config_value from sys_config where config_key='realtime_data_save_days'";
			Integer days = sqlQueryService.getInteger(sql);

			// 查出历史数据（天数通过参数设置中设置）
			Query query = new Query();
			String date = DateUtil.dateAddDay(-days, "yyyy-MM-dd HH");
			query.addCriteria(Criteria.where("time").lte(date + ":59:59"));
			List<JSONObject> list = mongoTemplate.find(query, JSONObject.class, WSMS_REALTIME_DATA_TABLE);

			// 删除30前一天数据
			mongoTemplate.remove(query, WSMS_REALTIME_DATA_TABLE);

			for (JSONObject wompAlarm : list) {
				mongoTemplate.insert(wompAlarm, WSMS_REALTIME_DATA_TABLE
						+ DateUtil.formatDate(DateUtil.parseDate(wompAlarm.getString("time"), "yyyy-MM-dd"), "yyyyMM"));
			}
			System.out.println(date);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}